<template>
  <div class="chatAppBody" style="height: 900px">
    <div style="padding-bottom:10px">
      <el-button type="primary" @click="clear">清空对话</el-button>
    </div>
    <div class="chatBox">

      <MessageView :message="{content:'您好，我是智能AI心理咨询师，你可以向我倾诉烦恼，或者咨询心理健康相关问题',tag:1}"></MessageView>
      <div v-for="(item,index) in messageList" :key="index">
        <MessageView :message="item" @change="scrollBottom"></MessageView>
      </div>
    </div>
    <div class="chatArea">
      <el-input type="textarea" style="padding-top: 10px;padding-right: 20px" v-model="sendContent" :rows="3"></el-input>
      <div>
        <el-button type="primary" @click="sendMess" style="margin-top: 10px;">发送</el-button>
      </div>
    </div>

  </div>
</template>

<script>
import MessageView from "@/views/chat/message";

import CryptoJS from 'crypto-js'

function getUrl() {
  const apiKey = "d2a796c47f9322a548b68a6aef3f0faf";
  const apiSecret = "NzJmMDM2NmViZTU5NWNmN2ZjOGEwMzhk";
  var url = 'wss://spark-api.xf-yun.com/v3.5/chat';
  var host = location.host
  var date = new Date().toUTCString()
  var algorithm = 'hmac-sha256'
  var headers = 'host date request-line'
  var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v3.5/chat HTTP/1.1`

  var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret)
  var signature = CryptoJS.enc.Base64.stringify(signatureSha)
  var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`
  var authorization = btoa(authorizationOrigin)
  url = `${url}?authorization=${authorization}&date=${date}&host=${host}`
  return url
}


function getHeart() {
  window.heart();
  // console.log(date)
  console.log("heart")
}

export default {
  name: 'chatView',
  components: {MessageView},
  data() {
    return {
      messageList: [],
      circleUrl: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      sendContent: "",
      socket: null,
      heartbeatInterval: null,
      data: "",
      i: 0
    }
  },
  methods: {
    //滚动到底部
    scrollBottom() {
      var container = this.$el.querySelector(".chatBox");
      container.scrollTop = container.scrollHeight;
    },

    sendMess() {
      this.messageList.push({content: this.sendContent, tag: 0})
      this.send(this.sendContent)
      this.scrollBottom()
      // setInterval(function (){
      //   console.log("time:15s")
      //   // console.log(url)
      //   getHeart();
      // },15000);
    },

    init() {
      console.log("websocket")
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {

        let path = getUrl(); // 请求路径
        this.socket = new WebSocket(path);
        this.socket.onopen = this.open.bind(this);
        this.socket.onerror = this.error.bind(this);
        this.socket.onclose = this.close.bind(this);
        this.socket.onmessage =
          function (msg) {
            let result = JSON.parse(msg.data)
            if (result.header.code == 0) {
              if (result.payload.choices.seq == 0) {
                this.messageList.push({tag: 1, content: result.payload.choices.text[0].content})
              } else {
                let l = this.messageList.length;
                this.messageList[l - 1].content = this.messageList[l - 1].content + result.payload.choices.text[0].content;
              }
            }

          }.bind(this);
      }
    },

    open() {
      console.log("socket连接成功");
      if (this.socket) {
        this.data = ""
        console.log("发送信息")
        var params = {
          "header": {
            "app_id": "00055ebc",
          },
          "parameter": {
            "chat": {
              "domain": "generalv3.5",
              "temperature": 0.5,
              "max_tokens": 1024
            }
          },
          "payload": {
            "message": {
              "text": []
            }
          }
        }
        params.payload.message.text.push({"role": "system", "content": "你现在是一名心理咨询师"})
        params.payload.message.text.push({"role": "user", "content": this.sendContent})
        // this.socket.send("")
        this.socket.send(JSON.stringify(params));
        this.sendContent = ""
      }
      // this.startHeartbeat()
      // this.send("")
    },

    error(err) {
      console.log(err)
      console.log(JSON.stringify(err))
      console.log("连接错误");
      // alert(this.socket)
      // this.close()
      // this.init()
      // this.socket.close()
    },

    send(data) {
      this.init()
    },

    close() {
      console.log("socket已经关闭");
    },

    clear(){
      this.messageList=[];
    }

  },
  created: function () {
    // this.init()
  },
  mounted() {
    window.heart = this.init
  }
}
</script>

<style lang="scss">
.chatAppBody {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: white;
  width: 98%;
  padding-top: 0;
}

.chatBox {
  flex: 1;
  padding: 0 5px;
  overflow: scroll;
  overflow-x: hidden;
  overflow-y: auto;
  background: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%);
  //background: linear-gradient(135deg,rgb(57,167,176),rgb(56,183,145));
  border-radius: 20px 15px 10px 10px;
}

.chatBox::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}



.chatArea {
  //margin: 0 10px 10px;
  //display: flex;
  //padding: 6px 5px;
  //align-items: center;
  //flex: 1;
  //border-radius: 10px;
  background: #fff;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
